package com.leadingsoft.pwxk.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.leadingsoft.pwxk.common.PagingPlugin;
import com.leadingsoft.pwxk.common.PagingPluginAssist;
import com.leadingsoft.pwxk.converter.PwBaseInfoConverter;
import com.leadingsoft.pwxk.dto.CategoryDto;
import com.leadingsoft.pwxk.dto.PagingTableDto;
import com.leadingsoft.pwxk.dto.PwBaseInfoDto;
import com.leadingsoft.pwxk.dto.SearchDto;
import com.leadingsoft.pwxk.enums.EDrainCountType;
import com.leadingsoft.pwxk.excel.CommonHandleExcel;
import com.leadingsoft.pwxk.excel.ExcelUtil;
import com.leadingsoft.pwxk.model.QBaseInfo;
import com.leadingsoft.pwxk.model.QLatestData;
import com.leadingsoft.pwxk.model.QPwBaseInfo;
import com.leadingsoft.pwxk.repository.PwBaseInfoRepository;
import com.leadingsoft.pwxk.service.CategoryService;
import com.leadingsoft.pwxk.service.PwBaseInfoService;
import com.querydsl.core.BooleanBuilder;
import com.querydsl.core.Tuple;
import com.querydsl.core.types.OrderSpecifier;
import com.querydsl.jpa.impl.JPAQuery;

import io.swagger.annotations.ApiOperation;

/**
 * @author: lipan 2018年5月17日
 * @description: ( 排污单位基本信息 )
 * 
 */

@Service
public class PwBaseInfoServiceImpl implements PwBaseInfoService {

	@Autowired
	private PwBaseInfoRepository pwBaseInfoRepository;

	@Autowired
	private PwBaseInfoConverter pwBaseInfoConverter;
	@Autowired
	CategoryService categoryService;
	// 排污单位
	QPwBaseInfo qPwBaseInfo = QPwBaseInfo.pwBaseInfo;
	// 企业注册信息
	QBaseInfo qBaseInfo = QBaseInfo.baseInfo;

	QLatestData qLatestData = QLatestData.latestData;

	@Autowired
	private EntityManager em;

	void builder(BooleanBuilder builder, SearchDto searchDto) {
		if (searchDto == null) {
			return;
		}
		if (StringUtils.isNotBlank(searchDto.getHyname())) {
			builder.and(qPwBaseInfo.hyname.eq(searchDto.getHyname()));
		}
		if (StringUtils.isNotBlank(searchDto.getDevcompany())) {
			builder.and(qPwBaseInfo.devcompany.eq(searchDto.getDevcompany()));
		}
	}

	@SuppressWarnings("rawtypes")
	@Override
	public PagingTableDto<PwBaseInfoDto> list(SearchDto searchDto) {
		JPAQuery<Tuple> query = new JPAQuery<>(em);
		query.select(qPwBaseInfo.devcompany, qPwBaseInfo.hyname, qPwBaseInfo.creditcode, qPwBaseInfo.isoperaname,
				qPwBaseInfo.isspecialname, qPwBaseInfo.dataid, qBaseInfo.name_region, qPwBaseInfo.operatime);

		query.from(qLatestData).leftJoin(qPwBaseInfo).on(qLatestData.dataid.eq(qPwBaseInfo.dataid)).leftJoin(qBaseInfo)
				.on(qPwBaseInfo.enterid.eq(qBaseInfo.enterid));
		if (searchDto != null) {
			/*
			 * if (StringUtils.isNotBlank(searchDto.getHyid())) {
			 * query.where(qBaseInfo.code_trade.eq(searchDto.getHyid())); }
			 */
			if (StringUtils.isNotBlank(searchDto.getHyid())) {
				List<CategoryDto> childs = categoryService.findByCodeChilds(searchDto.getHyid());
				List<String> hyids = new ArrayList<String>();
				List<String> result = new ArrayList<String>();
				if (childs.isEmpty()) {
					hyids.add(searchDto.getHyid());
				} else {
					childs.forEach(t -> {
						hyids.addAll(getAllHyid(t.getChilds(), t, result));
					});
				}
				query.where(qBaseInfo.code_trade.in(hyids));
			}
			if (null != searchDto.getHyids() && searchDto.getHyids().length > 0) {
				query.where(qBaseInfo.code_trade.in(searchDto.getHyids()));
			}
			if (StringUtils.isNotBlank(searchDto.getDevcompany())) {
				query.where(qPwBaseInfo.devcompany.contains(searchDto.getDevcompany()));
			}
			if (StringUtils.isNotBlank(searchDto.getCodeRegion())) {
				query.where(qBaseInfo.code_region.eq(searchDto.getCodeRegion()));
			}
			if (StringUtils.isNotBlank(searchDto.getYear())) {
				query.where(
						qPwBaseInfo.operatime.substring(0, qPwBaseInfo.operatime.indexOf("-")).eq(searchDto.getYear()));
			}
		}
		List<PwBaseInfoDto> list = new ArrayList<>();
		OrderSpecifier[] orderSpecifier = { qPwBaseInfo.operatime.desc() };
		PagingPluginAssist pagingInfo = PagingPlugin.getPagingInfo(query, searchDto, orderSpecifier);
		List<Tuple> fetch = pagingInfo.getList();
		fetch.forEach(t -> {
			PwBaseInfoDto pwBaseInfoDto = new PwBaseInfoDto();
			pwBaseInfoDto.setDevcompany(t.get(qPwBaseInfo.devcompany));
			pwBaseInfoDto.setHyname(t.get(qPwBaseInfo.hyname));
			pwBaseInfoDto.setCreditcode(t.get(qPwBaseInfo.creditcode));
			pwBaseInfoDto.setIsoperaname(t.get(qPwBaseInfo.isoperaname));
			pwBaseInfoDto.setIsspecialname(t.get(qPwBaseInfo.isspecialname));
			pwBaseInfoDto.setRegionName(t.get(qBaseInfo.name_region));
			pwBaseInfoDto.setDataid(t.get(qPwBaseInfo.dataid));
			pwBaseInfoDto.setOperatime(t.get(qPwBaseInfo.operatime));
			list.add(pwBaseInfoDto);
		});
		PagingTableDto<PwBaseInfoDto> dto = new PagingTableDto<>();
		dto.setData(list);
		dto.setRecordsTotal(pagingInfo.getRecordsTotal());
		return dto;
	}

	@Override
	public PwBaseInfoDto get(@PathVariable(value = "id") Long id) {
		return pwBaseInfoConverter.toDto(pwBaseInfoRepository.findById(id));
	}

	@Override
	public PwBaseInfoDto get(String dataid) {
		return pwBaseInfoConverter.toDto(pwBaseInfoRepository.findByDataid(dataid));
	}

	@ApiOperation("污染物排放口统计 - 通用导出 excel")
	@RequestMapping(value = "export", method = RequestMethod.GET)
	public void listExcel(HttpServletResponse response, SearchDto searchDto,
			@RequestParam(value = "eGroup", defaultValue = "airCount") EDrainCountType eGroup,
			@RequestParam(value = "etype", defaultValue = "airCountOneTable") EDrainCountType etype,
			@RequestParam(value = "title", required = false) String title) {
		title = etype.getName();
		List<Map<String, Object>> datas = getData(searchDto, etype);
		List<String> titleFirst = new ArrayList<>();
		List<String> propertyList = Arrays
				.asList(new String[] { "no", "name_region", "entername", "entername", "tradesname" });
		List<String> titleList = Arrays.asList(new String[] { "序号", "地区", "许可证编号", "单位名称", "行业类别" });
		propertyList = new ArrayList<String>(propertyList);
		titleList = new ArrayList<String>(titleList);
		insertKey(eGroup, propertyList, titleList);
		for (int i = 0; i < propertyList.size(); i++) {
			titleFirst.add(title);
		}
		List<String[]> heads = new ArrayList<>();
		heads.add(titleFirst.toArray(new String[] {}));
		heads.add(titleList.toArray(new String[] {}));
		ExcelUtil.createWorkBook(title, heads, propertyList.toArray(new String[] {}), datas, response,
				new CommonHandleExcel(propertyList.size(), datas.size()), null);
	}

	private void insertKey(EDrainCountType eGroup, List<String> propertyList, List<String> titleList) {
		// TODO Auto-generated method stub

	}

	private List<Map<String, Object>> getData(SearchDto searchDto, EDrainCountType etype) {
		// TODO Auto-generated method stub
		return null;
	}

	private List<String> getAllHyid(List<CategoryDto> childs, CategoryDto parent, List<String> result) {
		if (null != childs && !childs.isEmpty()) {
			childs.forEach(t -> {
				getAllHyid(t.getChilds(), t, result);
			});
		}
		if (null != parent) {
			result.add(parent.getCode());
		}
		return result;
	}
}
